import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import java.io.IOException;
import java.sql.*;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    // 使用相同的数据库连接信息
    private static final String DB_URL = "jdbc:mysql://localhost:3306/baomu?useSSL=false&allowPublicKeyRetrieval=true";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456"; // 替换为您的MySQL密码

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("MySQL JDBC驱动已成功加载");
        } catch (ClassNotFoundException e) {
            System.err.println("无法加载MySQL JDBC驱动");
            e.printStackTrace();
            throw new RuntimeException("无法加载数据库驱动", e);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 验证输入
        if (username == null || username.trim().isEmpty() ||
                password == null || password.trim().isEmpty()) {

            redirectWithError(response, "用户名和密码不能为空");
            return;
        }

        // 验证用户登录
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            String sql = "SELECT u_id, u_name, u_role FROM user WHERE u_name = ? AND u_pwd = ?";

            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                stmt.setString(1, username);
                stmt.setString(2, password);

                try (ResultSet rs = stmt.executeQuery()) {
                    if (rs.next()) {
                        // 登录成功
                        int userId = rs.getInt("u_id");
                        String userName = rs.getString("u_name");
                        int userRole = rs.getInt("u_role");

                        // 创建会话
                        HttpSession session = request.getSession();
                        session.setAttribute("userId", userId);
                        session.setAttribute("userName", userName);
                        session.setAttribute("userRole", userRole);

                        // 设置会话超时时间（30分钟）
                        session.setMaxInactiveInterval(30 * 60);

                        System.out.println("用户登录成功: " + userName);

                        // 根据角色跳转到不同页面
                        if (userRole == 0) {
                            response.sendRedirect("employer-dashboard.jsp");
                        } else {
                            response.sendRedirect("nanny-dashboard.jsp");
                        }
                    } else {
                        // 登录失败
                        redirectWithError(response, "用户名或密码错误");
                    }
                }
            }
        } catch (SQLException e) {
            System.err.println("数据库错误: " + e.getMessage());
            redirectWithError(response, "系统错误，请稍后重试");
        }
    }

    private void redirectWithError(HttpServletResponse response, String errorMessage) throws IOException {
        String encodedError = java.net.URLEncoder.encode(errorMessage, "UTF-8");
        response.sendRedirect("login.jsp?error=" + encodedError);
    }
}